package com.example.lenovo.asia5b.my.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.lenovo.asia5b.commodity.activity.ServiceActivity;
import com.example.lenovo.asia5b.my.bean.BankBean;
import com.example.lenovo.asia5b.my.bean.BankTypeBean;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.util.DensityUtil;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.MoneyUtil;
import com.example.lenovo.asia5b.util.Setting;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import app.BaseActivity;
import fay.frame.ui.U;

import static com.example.lenovo.asia5b.util.SharedPreferencesUtils.getUserBean;
import static com.wushi.lenovo.asia5b.R.id.public_btn_left;


/**
 * 取现账户
 * Created by lenovo on 2017/6/22.
 */

public class AccessAccountActivity extends BaseActivity implements ICallBack, LoadingDalog.PasswordDialogInterface, MoneyUtil.MoneyInterface {
    private Button btn_withdrawals;
    private LoadingDalog loadingDalog;
    private EditText edit_money, edit_user_name, edit_yhzh, edit_sfzh;
    private String paypass;
    private Spinner spr_bank_type, spr_bank_one, spr_bank_two;
    private List<BankTypeBean> listBankTypes;
    private List<BankBean> listBanks;
    private List<String> listBankTypeNames;
    private List<String> listBankNameOnes;

    private String type_id = "";
    private String bank_id = "";

    private TextView txt_user_money;
    private CheckBox chb_protocol;
    private   MoneyUtil moneyUtil = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_access_account);
        initView();
        bankData();
        bankTypeData();
    }

    public void initView() {
        moneyUtil= new MoneyUtil(this);
        moneyUtil.moneyData();
        F.id(R.id.public_title_name).text(getResources().getString(R.string.access_account));
        F.id(R.id.public_txt_righe).text(getResources().getString(R.string.cash_record));
        F.id(public_btn_left).clicked(this);
        F.id(R.id.public_txt_righe).clicked(this);
        F.id(R.id.ll_xy).clicked(this);
        loadingDalog = new LoadingDalog(AccessAccountActivity.this);
        btn_withdrawals = (Button) findViewById(R.id.btn_withdrawals);
        btn_withdrawals.setOnClickListener(this);
        edit_money = (EditText) findViewById(R.id.edit_money);
        edit_user_name = (EditText) findViewById(R.id.edit_user_name);
        edit_yhzh = (EditText) findViewById(R.id.edit_yhzh);
        edit_sfzh = (EditText) findViewById(R.id.edit_sfzh);
        spr_bank_type = (Spinner) findViewById(R.id.spr_bank_type);
        spr_bank_one = (Spinner) findViewById(R.id.spr_bank_one);
        spr_bank_two = (Spinner) findViewById(R.id.spr_bank_two);
        txt_user_money = (TextView) findViewById(R.id.txt_user_money);
        chb_protocol = (CheckBox) findViewById(R.id.chb_protocol);
//        txt_user_money.setText(getUserBean().user_money);
        edit_money.addTextChangedListener(new EditChangedListener(edit_money));
        chb_protocol.setChecked(true);
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.btn_withdrawals:
                if (TextUtils.isEmpty(edit_money.getText().toString())) {
                    U.Toast(AccessAccountActivity.this,getResources().getString(R.string.qxjwbnwk));
                } else if (TextUtils.isEmpty(bank_id)) {
                    U.Toast(AccessAccountActivity.this, getResources().getString(R.string.ssyhbnwk));
                } else if (TextUtils.isEmpty(type_id)) {
                    U.Toast(AccessAccountActivity.this, getResources().getString(R.string.zhlxbnwk));
                } else if (TextUtils.isEmpty(edit_user_name.getText().toString())) {
                    U.Toast(AccessAccountActivity.this, getResources().getString(R.string.zhxmbnwk));
                } else if (TextUtils.isEmpty(edit_sfzh.getText().toString())) {
                    U.Toast(AccessAccountActivity.this, getResources().getString(R.string.sfzbnwk));
                } else if (TextUtils.isEmpty(edit_yhzh.getText().toString())) {
                    U.Toast(AccessAccountActivity.this, getResources().getString(R.string.yhzhbnwk));
                } else if (!chb_protocol.isChecked()) {
                    U.Toast(AccessAccountActivity.this, getResources().getString(R.string.qgxyhxy));
                } else {
                    if (!TextUtils.isEmpty(edit_money.getText().toString())) {
                        if (edit_money.getText().toString().substring(0,1).equals(".")) {
                            return;
                        }
                    }
                    if (getUserBean().paypass.equals("0")){
                        U.Toast(AccessAccountActivity.this, getString(R.string.none_pay_pwd));
                        intent = new Intent(AccessAccountActivity.this, SetPayPassword.class);
                        startActivity(intent);
                        return;
                    }
                    loadingDalog.showPassword(edit_money.getText().toString());
                }
                break;
            case public_btn_left:
                finish();
                break;
            case R.id.public_txt_righe:
                intent = new Intent(AccessAccountActivity.this,CashRecordActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_xy:
                intent = new Intent(this, ServiceActivity.class);
                intent.putExtra("xy","2");
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            if (action == 0) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            U.Toast(AccessAccountActivity.this, getResources().getString(R.string.cg));
                            Intent intent = new Intent();
                            intent.putExtra("222",2222);
                            AccessAccountActivity.this.setResult(0, intent);
                            finish();
                        } else if (state == 1) {
                            U.Toast(AccessAccountActivity.this, getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(AccessAccountActivity.this, getResources().getString(R.string.cscw));
                        } else if (state == 3) {
                            U.Toast(AccessAccountActivity.this, getResources().getString(R.string.wdl));
                        } else if (state == 4) {
                            U.Toast(AccessAccountActivity.this, getResources().getString(R.string.import_cash_money));
                        } else if (state == 5) {
                            U.Toast(AccessAccountActivity.this, getResources().getString(R.string.qxjebndyzhye));
                        } else if (state == 6) {
                            U.Toast(AccessAccountActivity.this, getResources().getString(R.string.ssyhbnwk));
                        } else if (state == 7) {
                            U.Toast(AccessAccountActivity.this, getResources().getString(R.string.zhlxbnwk));
                        } else if (state == 8) {
                            U.Toast(AccessAccountActivity.this, getResources().getString(R.string.zhxmbnwk));
                        } else if (state == 9) {
                            U.Toast(AccessAccountActivity.this,getResources().getString(R.string.sfzbnwk));
                        } else if (state == 10) {
                            U.Toast(AccessAccountActivity.this, getResources().getString(R.string.yhzhbnwk));
                        } else if (state == 11) {
                            U.Toast(AccessAccountActivity.this,getResources().getString(R.string.qgxyhxy));
                        } else if (state == 12) {
                            U.Toast(AccessAccountActivity.this, getResources().getString(R.string.pay_the_pa_sword_cannot_be_empty));
                        } else if (state == 13) {
                            U.Toast(AccessAccountActivity.this, getResources().getString(R.string.ndzfmmyw));
                        }else if (state == 15) {
                            U.Toast(AccessAccountActivity.this, getString(R.string.none_pay_pwd));
                            Intent intent = new Intent(AccessAccountActivity.this, SetPayPassword.class);
                            startActivity(intent);
                            loadingDalog.dismiss();
                            loadingDalog.passwordDialog = null;
                        }
                    } catch (Exception e) {
                    }
                } else {
                }
                loadingDalog.clearPassword();
                loadingDalog.dismiss();
            } else if (action == 1) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            JSONArray bank = json.getJSONArray("bank");
                            listBanks = Logic.getListToBean(bank, new BankBean());
                            showBank();
                        } else if (state == 1) {
                            U.Toast(AccessAccountActivity.this,getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(AccessAccountActivity.this, getResources().getString(R.string.cscw));
                        }
                    } catch (Exception e) {
                    }
                }
            } else if (action == 2) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            JSONArray type = json.getJSONArray("type");
                            listBankTypes = Logic.getListToBean(type, new BankTypeBean());
                            showBankType();
                        } else if (state == 1) {
                            U.Toast(AccessAccountActivity.this,getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(AccessAccountActivity.this, getResources().getString(R.string.cscw));
                        }
                    } catch (Exception e) {
                    }
                }
            }
        }
    };

    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }

    /**
     * 提现接口
     */
    public void withdrawalsData() {
        loadingDalog.show();
        //提现金额
        String money = edit_money.getText().toString();
        //账户类型
        String type = type_id;
        //所属银行
        String bank = bank_id;
        //账号姓名
        String user_name = edit_user_name.getText().toString();
        //银行账号
        String yhzh = edit_yhzh.getText().toString();
        //身份证号
        String sfzh = edit_sfzh.getText().toString();
        //用户协议
        String cashAgreement = "1";
        if (money.indexOf(".")!=-1) {
            float aa = Float.parseFloat(money);
            aa = DensityUtil.getScale(aa);
            money = aa+"";
        }
        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.WITHDRAWALS;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id" + user_id, "money" + money, "type" + type, "bank" + bank, "user_name" + user_name, "yhzh" + yhzh, "sfzh" + sfzh, "cashAgreement" + cashAgreement, "paypass" + paypass, "time" + time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("money", money);
            parmaMap.put("type", type);
            parmaMap.put("bank", bank);
            parmaMap.put("user_name", user_name);
            parmaMap.put("yhzh", yhzh);
            parmaMap.put("sfzh", sfzh);
            parmaMap.put("cashAgreement", cashAgreement);
            parmaMap.put("paypass", paypass);
            parmaMap.put("time", time);
            parmaMap.put("sign", md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 0);
        } catch (Exception e) {

        }

    }

    /**
     * 银行列表
     */
    public void bankData() {
        Map<String, String> parmaMap = new HashMap<String, String>();
        String url = Setting.BANK;
        parmaMap.put("type","0");
        parmaMap.put("entry","0");
        JsonTools.getJsonAll(this, url, parmaMap, 1);
    }


    /**
     * 银行类型列表
     */
    public void bankTypeData() {
        Map<String, String> parmaMap = new HashMap<String, String>();
        String url = Setting.BANK_TYPE;
        JsonTools.getJsonAll(this, url, parmaMap, 2);
    }

    @Override
    public void gainPasswor(String strPasswor) {
        paypass = strPasswor;
        withdrawalsData();

    }

    //银行类型选择器
    public void showBankType() {
        getBankType();
        ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(AccessAccountActivity.this,
                R.layout.simple_list_item,
                listBankTypeNames);
        spr_bank_type.setAdapter(adapter1);
        spr_bank_type.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                type_id = listBankTypes.get(arg2).type_id.trim();
            }

            public void onNothingSelected(AdapterView<?> arg0) {
                arg0.setVisibility(View.VISIBLE);
            }
        });
    }

    //  通过遍历集合获得银行类型的名字
    private void getBankType() {
        listBankTypeNames = new ArrayList<String>();
        for (BankTypeBean bean : listBankTypes) {
            String type_name = bean.type_name;
            listBankTypeNames.add(type_name);
        }
    }

    //银行选择器
    public void showBank() {
        getPriovince();
        ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(AccessAccountActivity.this,
                R.layout.simple_list_item,
                listBankNameOnes);
        spr_bank_one.setAdapter(adapter1);
        spr_bank_one.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

                final BankBean bean = listBanks.get(arg2);
                List<String> citys = getBanks(bean);
                ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(AccessAccountActivity.this,
                        R.layout.simple_list_item,
                        citys);
                spr_bank_two.setAdapter(adapter2);
                spr_bank_two.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
                    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                        if (null != bean.chile.get(arg2)) {
                            bank_id = bean.chile.get(arg2).bank_id;
                        }
                    }

                    public void onNothingSelected(AdapterView<?> arg0) {
                    }
                });

            }

            public void onNothingSelected(AdapterView<?> arg0) {
                arg0.setVisibility(View.VISIBLE);
            }
        });
    }

    //  通过遍历集合获得银行的名字 --备用赋值给Spinner1
    private void getPriovince() {
        listBankNameOnes = new ArrayList<String>();
        for (BankBean bean : listBanks) {
            String cityname = bean.bank_name;
            listBankNameOnes.add(cityname);
        }
    }

    //  通过市获得区--备用赋值给Spinner2
    private List<String> getBanks(BankBean bean) {
        List<String> listBankNameTwos = new ArrayList<String>();
        if (null != bean.chile) {
            List<BankBean> citys = bean.chile;
            for (BankBean citys2 : citys) {
                String cityName = citys2.bank_name;
                listBankNameTwos.add(cityName);
            }
        }
        return listBankNameTwos;
    }

    @Override
    public void money(String user_money,String pay_points) {
        txt_user_money.setText(user_money);
    }
}